package com.innovations.framework.security.handle;

import com.innovations.framework.web.service.UserDetailsServiceImpl;
import java.util.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        UserDetails userDetails = userDetailsService.loadUserByUsername(authentication.getName());

        // 这里进行实际的身份验证逻辑，例如查询数据库 todo 这里需要调整
        if ("admin".equals(username)) {
            CustomAuthentication customAuthentication = new CustomAuthentication(username, password, Collections.emptyList());
            customAuthentication.setAuthenticated(true);
            customAuthentication.setPrincipal(userDetails);
            return customAuthentication;
        } else {
            throw new BadCredentialsException("用户名或密码错误");
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return CustomAuthentication.class.isAssignableFrom(authentication);
    }
}